﻿using System;
using System.IO;
using System.Text;

namespace PSE.Deployment.ConfigurationManager.Engine.Logging
{
	public static class OperationLog
	{
		static DateTime _logTimestamp = DateTime.Now;

		static string _logPath = Path.Combine(Environment.GetEnvironmentVariable("TEMP", EnvironmentVariableTarget.Machine), System.Configuration.ConfigurationSettings.AppSettings["LogFilePath"]);
		public static string LogPath
		{
			get { return OperationLog._logPath; }
			set { OperationLog._logPath = value; }
		}

		public static void Write(string logText)
		{
			string logFilePath = OperationLog.LogPath;

			if (!String.IsNullOrEmpty(logFilePath))
			{
				if (!Directory.Exists(logFilePath))
				{
					try
					{
						Directory.CreateDirectory(logFilePath);
					}
					catch
					{
						return;
					}
				}

				logFilePath += @"\" + string.Format("ConfigurationManagerLog_{0}.txt", _logTimestamp.ToString("yyyyMMddHHmmss"));

				StreamWriter sw = new StreamWriter(logFilePath, true);

				logText = DateTime.Now.ToString("HH:mm:ss") + ": " + logText + Environment.NewLine;	
				sw.Write(logText);
				sw.Close();
			}
			else
				throw new InvalidOperationException("Cannot write log, LogPath is empty.");
		}

		public static void Write(string logText, Exception ex)
		{
			StringBuilder sb = new StringBuilder();
			sb.Append(logText);

			if (ex != null)
			{
				sb.AppendLine();
				sb.AppendLine("-----------------------------------------------------------------------------");
				sb.AppendLine(string.Format("Details: {0}", ex.ToString()));
				sb.AppendLine("-----------------------------------------------------------------------------");
			}

			Write(sb.ToString());
		}
	}
}